package com.algorithm.ch1.yjx.array;

import java.util.Arrays;

/**
 * @author yuanjianxin
 * @date 2018/8/13 11:36
 */
public class Rotate {

    public static void main(String[] args) {
//        输入: [1,2,3,4,5,6,7] 和 k = 3
//        输出: [5,6,7,1,2,3,4]
        int[] arr = {1, 2, 3, 4, 5, 6,7};
        int k = 3;
        System.out.print("k=" + k + ",移动前");
        System.out.println(Arrays.toString(arr));
        rotate(arr, k);
        System.out.print("==移动后==");
        System.out.println(Arrays.toString(arr));


    }

    public static void rotate(int[] nums, int k) {
        k = k % nums.length;
        //前半段交换
        reverse(nums, 0, nums.length - k - 1);
        //后半段交换
        reverse(nums, nums.length - k, nums.length - 1);

        reverse(nums, 0, nums.length - 1);
    }

    private static void reverse(int[] nums, int start, int end) {
        while (start < end) {
            int temp = nums[start];
            nums[start] = nums[end];
            nums[end] = temp;
            start++;
            end--;
        }
    }
}
